import os
import random
import sys

from PyQt5.QtCore import pyqtSlot, QObject, QUrl, QFileInfo, pyqtSignal
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton


class TMainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        # 设置程序宽高
        self.resize(850, 700)

        # ---Web widget and layout---
        self.mpJSWebView = QWebEngineView(self)
        self.pWebChannel = QWebChannel(self.mpJSWebView.page())
        self.pInteractObj = TInteractObj(self)
        self.pWebChannel.registerObject("interactObj", self.pInteractObj)

        self.mpJSWebView.page().setWebChannel(self.pWebChannel)
        # self.mpJSWebView.page().load(QUrl(QFileInfo('temp.html').absoluteFilePath()))
        self.mpJSWebView.page().load(QUrl(QFileInfo('view/index.html').absoluteFilePath()))

        self.testButton = QPushButton("python按钮1")
        self.testButton.clicked.connect(self.testButtonCallback)

        self.testButton2 = QPushButton("python按钮2")
        self.testButton2.clicked.connect(self.testButton2Callback)

        # 渲染页面
        grid = QGridLayout()
        grid.setSpacing(0)
        grid.addWidget(self.mpJSWebView, 1, 1, 1, 1)
        grid.addWidget(self.testButton, 2, 1, 1, 1)
        grid.addWidget(self.testButton2, 3, 1, 1, 1)
        grid.setContentsMargins(0, 0, 0, 0)
        self.setLayout(grid)

    def testButtonCallback(self):
        print("click testButton1:", end='')
        message = "Python send string to Html:" + str(random.randint(0, 9))
        print(message)
        self.mpJSWebView.page().runJavaScript("output('%s')" % message)

    def testButton2Callback(self):
        print("click testButton2:", end='')
        message = str(random.randint(0, 9))
        print(message)
        self.pInteractObj.pyMessage.emit(message)


class TInteractObj(QObject):
    # SigReceivedMessFromJS = pyqtSignal(str)
    pyMessage = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)

    @pyqtSlot(str)
    def jsPostMessage(self, strParameter):
        print('jsPostMessage(%s) from Html' % strParameter)
        # self.SigReceivedMessFromJS.emit(strParameter)

    # @pyqtSlot(result=str)
    # def fun(self):
    #     print('TInteractObj.fun()')
    #     return 'hello'


if __name__ == '__main__':
    # 配置web调试
    os.putenv("QTWEBENGINE_REMOTE_DEBUGGING", "9223")
    app = QApplication(sys.argv)

    dlg = TMainWindow()
    dlg.show()

    app.exec_()
